#  Copyright (C) 2010 Luca Piccinelli
# 
#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#  
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#  
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.
   

'''
Created on Apr 24, 2011

@author: picci
'''

from glob import glob
from pypelab.common.patterns import Borg
from ctypes import CDLL
import logging
import os

PLUGINS_DEFAULT_PATH = os.path.join("../", "plugins")
PLUGINS_PATH_SEPARATOR = ";" 

class PluginManager(Borg):
    def __init__(self, plugins_paths = PLUGINS_DEFAULT_PATH):
        super().__init__()
        self._plugins_paths = plugins_paths.split(PLUGINS_PATH_SEPARATOR)
        if '_plugins_map' not in self.__dict__:
            self._plugins_map = {}
        self.refresh()
    
    def refresh(self):
        for path in self._plugins_paths:
            for plugin_lib_name in glob(os.path.join(path, "*.so")):
                plugin_name = os.path.basename(plugin_lib_name)
                if plugin_name not in self._plugins_map: 
                    self._plugins_map[plugin_name] = CDLL(plugin_lib_name)
                else:
                    logging.warn('trying to load {0} plugin: already exists in the plugin manager'.format(plugin_name))                              
        
